var socket_io = require('socket.io');
var socketIo = {};


// 聊天人群
let userList = {}

// 聊天记录
let infoSpace = []

// 获取io
socketIo.getSocketio = function(server) {
    // server => http(s)
    var io = socket_io.listen(server);
    let sum = 0; // 人数
    io.sockets.on('connection',function(socket){
        console.log('连接成功!');
        socket.on('login', function(data) {
            if(!userList[data.user]){
                userList[data.user] = data.pwd;
                sum += 1;
                io.sockets.emit('login', sum);
                io.sockets.emit('upUserList', Object.keys(userList));
                io.sockets.emit('receive', infoSpace);
            }else{
                if(userList[data.user] === data.pwd){
                    sum += 1;
                    io.sockets.emit('login', sum);
                    io.sockets.emit('upUserList', Object.keys(userList));
                    io.sockets.emit('receive', infoSpace);
                }else{
                    //  单播
                    socket.emit('message', {msg: '密码错误！'});
                }
            }
        });
        socket.on('send', data => {
            infoSpace.push(data);
            io.sockets.emit('receive', infoSpace);
        })
        socket.on('close', data => {
            if(data){
                delete userList[data];
                console.log(data+'用户断开了！');
                sum -= 1;
                io.sockets.emit('login', sum);
                io.sockets.emit('upUserList', Object.keys(userList));
            }
        })
    });
}

module.exports = socketIo;